package com.gm.commonlib.module.image.takeimage;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;

import com.gm.commonlib.module.image.BitmapUtils;
import com.gm.commonlib.module.image.ImageUtil;
import com.gm.commonlib.util.fileUtil.FileUtils;
import com.gm.commonlib.util.stringUtils.StringUtils;
import com.gm.commonlib.util.timeUtils.DateTimeUtils;
import com.gm.commonlib.views.toast.ToastUtil;

import java.io.File;
public class PhotoUploadHelper {

    public final static int MAX_LIMIT_SIZE = 1 * 1024 * 1024;

    public PhotoUploadHelper() {
    }

    /**
     * 上传已选择的图片
     *
     * @param data
     * @param catchFolder
     * @param listener
     */
    public void afterResultUploadSelectPicture(Context context, Intent data, File catchFolder, PictureSelectListener listener) {
        handleActivityResult(context, data, catchFolder, listener);
    }

    public static String compressAndSaveFile(File catchFolder, String orgFilePath) {
        return compressAndSaveFile(catchFolder, orgFilePath, true);
    }
    public static String getFileNameExceptExt(String fileName) {
        if (StringUtils.isNotBlank(fileName)) {
            int dotIndex = fileName.lastIndexOf(".");
            if (dotIndex != -1) {
                String temp = fileName.substring(0, dotIndex);
                if (StringUtils.isNotBlank(temp)) {
                    return temp;
                } else {
                    return fileName.substring(1);
                }
            }
        }
        return fileName;
    }

    public static String compressAndSaveFile(File catchFolder, String orgFilePath, boolean keepExtName) {
        File srcFile = new File(orgFilePath);
        if (srcFile.exists()) {
            String fileName = new File(orgFilePath).getName();
            if (!keepExtName) {//是否保存扩展名
                fileName = getFileNameExceptExt(fileName);
            }
            if (StringUtils.isBlank(fileName)) {
                fileName = DateTimeUtils.formatDuring(System.currentTimeMillis());
            }
            String filePath = catchFolder.getAbsolutePath() + File.separator;

            if (srcFile.length() > MAX_LIMIT_SIZE) {
                Bitmap bm1 = ImageUtil.decodeFile(orgFilePath);
                if (bm1 == null) {
                    ToastUtil.showToast("图片解析失败，请重新拍摄或选择");
                    return "";
                }
                Bitmap bm3 = BitmapUtils.rotate(bm1, BitmapUtils.getBitmapDegree(orgFilePath));
                byte[] bytes = ImageUtil.compressByQuality(bm3, MAX_LIMIT_SIZE / 1024);

                FileUtils.createSDFile(bytes, filePath, fileName);

                try {
                    ImageUtil.recycleBitmap(bm1);
                    ImageUtil.recycleBitmap(bm3);
                } catch (Throwable throwable) {
                    throwable.printStackTrace();

                }

                return filePath + fileName;
            } else {
                try {
                    return FileUtils.copyFile(new File(orgFilePath), new File(filePath), fileName).getAbsolutePath();
                } catch (Exception e) {
                    e.printStackTrace();

                }
            }
        }
        ToastUtil.showToast("压缩图片失败，请检测是否具有写文件权限(或者图片不存在)");
        return "";
    }


    /**
     * 上传已选择的图片
     *
     * @param data
     * @param catchFolder
     * @param listener
     */
    public static void handleActivityResult(Context context, Intent data, File catchFolder, PictureSelectListener listener) {
        if (data == null) {
            ToastUtil.showToast("procActivityResult[参数错误:data->null]");
            return;
        }
        if (catchFolder == null) {
            ToastUtil.showToast("procActivityResult[参数错误:billFolder->null]");
            listener.onPictureIsSelected(null,null);
            return;
        }
        String orgPicPath = data.getStringExtra(NameSpace.SelectPicture.KEY_PHOTO_PATH);
        if (StringUtils.isNotEmpty(orgPicPath)) {
            compress(catchFolder, orgPicPath, listener);
            if (data.getIntExtra(NameSpace.SelectPicture.PICTURE_FROM, NameSpace.SelectPicture.PICTURE_FROM_UNKNOWN) == NameSpace.SelectPicture.PICTURE_FROM_TACK) {
                //TODO 拍的照片, 删除拍照的原图，保留压缩图片
                try {
                    if (StringUtils.isNotEmpty(orgPicPath)) {
                        FileUtils.delFile(orgPicPath);
                    }
                } catch (Exception e) {
                }
            }
        } else {
            Log.e("FKH", ">>> picPath is empty!!!");
            listener.onPictureIsSelected(null,null);
        }

    }

    public static void compress(File catchFolder, String orgPicPath, PictureSelectListener listener) {
        if (catchFolder == null || TextUtils.isEmpty(orgPicPath)) {
            listener.onPictureIsSelected(null,null);
            return;
        }
        if (!catchFolder.exists()) {
            catchFolder.mkdirs();
        }
        String picPath = compressAndSaveFile(catchFolder, orgPicPath);
        if (listener != null) {
            if (TextUtils.isEmpty(picPath)) {
                listener.onPictureIsSelected(null,null);
                return;
            }

            Bitmap bm1 = ImageUtil.decodeFile(picPath);
            if (bm1==null){
                listener.onPictureIsSelected(null, picPath);
                return;
            }
            Bitmap bm = ImageUtil.compressBySize(bm1, 200.0f, 200.0f);
            listener.onPictureIsSelected(bm, picPath);
            ImageUtil.recycleBitmap(bm1);
        }
    }

    public interface PictureSelectListener {
        boolean deleteOrgPicture();

        void onPictureIsSelected(Bitmap bitmap, String localPath);
    }

}
